package com.controller.lib.net
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.logging.HttpLoggingInterceptor
import okio.BufferedSink
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import timber.log.Timber
import java.io.File
import java.io.FileInputStream
import java.util.concurrent.TimeUnit
/**
 *    @author : GeRui
 *    date   : 2025/6/18 15:43
 *    desc   :
 *    version: 1.0
 */
 object RetrofitClient {
  // 基础配置
  private const val TIME_OUT = 30L // 超时时间30秒
  private var baseUrl = Api.BASE_SCOPE_URL

  // 获取Retrofit实例
  public val retrofit: Retrofit by lazy {
    Retrofit.Builder()
      .baseUrl(baseUrl)
      .client(okHttpClient)
      .addConverterFactory(GsonConverterFactory.create(gson))
      .build()
  }

  // Gson配置
  private val gson: Gson by lazy {
    GsonBuilder()
      .setDateFormat("yyyy-MM-dd HH:mm:ss")
      .create()
  }

  // OkHttpClient配置
  private val okHttpClient: OkHttpClient by lazy {
    OkHttpClient.Builder().apply {
      Timber.d("RetrofitClient: baseUrl = $baseUrl")
      connectTimeout(TIME_OUT, TimeUnit.SECONDS)
      readTimeout(TIME_OUT, TimeUnit.SECONDS)
      writeTimeout(TIME_OUT, TimeUnit.SECONDS)
      addInterceptor(loggingInterceptor)
      // 添加公共参数/头拦截器
//      addInterceptor { chain ->
//        val original = chain.request()
//        val request = original.newBuilder()
//          .header("Accept", "application/json")
//          .header("Content-Type", "application/json")
//          .method(original.method, original.body)
//          .build()
//        chain.proceed(request)
//      }
    }.build()
  }

  // 日志拦截器
  private val loggingInterceptor by lazy {
    HttpLoggingInterceptor().apply {
      level = HttpLoggingInterceptor.Level.BODY
    }
  }

  /**
   * 初始化方法
   * @param baseUrl 基础URL
   * @param debug 是否调试模式
   */
  fun init(baseUrl: String, debug: Boolean = false) {
    this.baseUrl = baseUrl
    if (!debug) {
      loggingInterceptor.level = HttpLoggingInterceptor.Level.NONE
    }
  }

  /**
   * 创建API服务
   */
  inline fun <reified T> createService(): T = retrofit.create(T::class.java)

  /**
   * 基础API响应封装
   */
  data class ApiResponse<T>(
    val code: Int,
    val message: String? = null,
    val data: T? = null
  ) {

  }

  /**
   * 带进度监听的上传RequestBody
   */
  class ProgressRequestBody(
    private val file: File,
    private val contentType: String,
    private val progressListener: (Int) -> Unit
  ) : RequestBody() {
    override fun contentType() = "$contentType/*".toMediaTypeOrNull()

    override fun contentLength() = file.length()

    override fun writeTo(sink: BufferedSink) {
      val buffer = ByteArray(8192)
      var uploaded = 0L
      FileInputStream(file).use { inputStream ->
        var read: Int
        while (inputStream.read(buffer).also { read = it } != -1) {
          uploaded += read
          sink.write(buffer, 0, read)
          progressListener((uploaded.toFloat() / contentLength() * 100).toInt())
        }
      }
    }
  }
}